#include <gtk/gtk.h>

// 定义自定义控件类型
typedef struct _CustomDrawingWidget CustomDrawingWidget;
typedef struct _CustomDrawingWidgetClass CustomDrawingWidgetClass;

struct _CustomDrawingWidget {
    GtkWidget parent_instance;
};

struct _CustomDrawingWidgetClass {
    GtkWidgetClass parent_class;
};

// 声明类型宏
G_DEFINE_TYPE(CustomDrawingWidget, custom_drawing_widget, GTK_TYPE_WIDGET)

// 重写 snapshot 方法
static void custom_drawing_widget_snapshot(GtkWidget *widget, GtkSnapshot *snapshot) {
    // 获取小部件的分配区域
    GtkAllocation allocation;
    gtk_widget_get_allocation(widget, &allocation);

    // 创建一个 Cairo 上下文
    graphene_rect_t grec1 = GRAPHENE_RECT_INIT(0, 0, allocation.width, allocation.height);
    cairo_t *cr = gtk_snapshot_append_cairo(snapshot, &grec1);

    // 绘制背景颜色
    GdkRGBA rgba1 = {0.9, 0.9, 0.9, 1};
    gdk_cairo_set_source_rgba(cr, &rgba1);
    cairo_rectangle(cr, 0, 0, allocation.width, allocation.height);
    cairo_fill(cr);

    // 绘制一个红色矩形
    GdkRGBA rgba2 = {1, 0, 0, 1};
    gdk_cairo_set_source_rgba(cr, &rgba2);
    cairo_rectangle(cr, 50, 50, 100, 100);
    cairo_fill(cr);

    // 绘制一些文本
    PangoLayout *layout = pango_layout_new(gtk_widget_get_pango_context(widget));
    pango_layout_set_text(layout, "Hello, GTK 4!", -1);
    pango_layout_set_font_description(layout, pango_font_description_from_string("Sans Bold 18"));

    GdkRGBA rgba3 = {0, 0, 0, 1};
    gdk_cairo_set_source_rgba(cr, &rgba3);
    pango_cairo_update_layout(cr, layout);
    pango_cairo_show_layout(cr, layout);

    // 清理资源
    g_object_unref(layout);
}

// 初始化自定义控件
static void custom_drawing_widget_init(CustomDrawingWidget *self) {
    // 初始化代码（如果有）
}

// 类初始化函数
static void custom_drawing_widget_class_init(CustomDrawingWidgetClass *klass) {
    GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
    widget_class->snapshot = custom_drawing_widget_snapshot;
}

// 激活应用程序
static void activate(GtkApplication *app, gpointer user_data) {
    GtkWidget *window;
    GtkWidget *custom_widget;

    window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "Custom Drawing Widget Example");
    gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);

    // 创建自定义绘制控件实例
    custom_widget = GTK_WIDGET(g_object_new(custom_drawing_widget_get_type(), NULL));
    gtk_window_set_child(GTK_WINDOW(window), custom_widget);

    // 显示窗口
    gtk_window_present(GTK_WINDOW(window));
}

int main(int argc, char **argv) {
    GtkApplication *app;
    int status;

    app = gtk_application_new("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
    g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
    status = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);

    return status;
}




